<template>
  <el-dialog
    :title="params.title"
    :visible.sync="params.visible"
    width="460px"
    append-to-body
  >
    <el-form ref="form" :model="formData" label-width="80px">
      <el-form-item label="Driver ID">
        <el-select v-model="formData.driverID" placeholder="请选择活动区域" @change="changeSelect(formData.driverID)">
          <el-option label="Ora" value="Ora" />
          <el-option label="MSSQL" value="MSSQL" />
          <el-option label="MySQL" value="MySQL" />
          <el-option label="PostgreSQL" value="PostgreSQL" />
        </el-select>
      </el-form-item>
      <compTable
        ref="paramTree"
        :show-search="false"
        :table-height="400"
        :show-icon="true"
        :table-data="paramTableInfo.data"
        :table-header="paramTableInfo.header"
        :expand-all="true"
        :highlight-current-row="false"
      />
    </el-form>
    <dialog-btn slot="footer">
      <el-button class="btn-left k_ceshi" @click="onTestClick">测试</el-button>
      <el-button class="btn-left k_jiankumb" @click="onLibraryModuleClick">建库模板</el-button>
    </dialog-btn>
    <buile-database v-if="buileDatabaseParams.visible" :params="buileDatabaseParams" />
  </el-dialog>
</template>
<script>
import Global from '@/../public/js/global'
import { dBConnectionTest } from '@/api/test.js'
import BuileDatabase from './BuileDatabase.vue'
export default {
  name: 'LibrarySetting',
  components: {
    BuileDatabase
  },
  props: {
    params: {
      type: Object,
      default: () => {
        return {
          title: '主库配置', // 当前窗口标题
          visible: true, // 是否显示当前窗口
          g_data: {} // 传入的对象
        }
      }
    }
  },
  data() {
    return {
      rows: [],
      formData: {
        driverID: 'Ora',
        // 双向绑定输入框数据
        inputPassWord: '',
        inputNumber: '',
        inputText: ''

      },
      // temp的数据
      tempDate: {
        mysql_temp: 'User_Name=root;Password=;Database=;Server=127.0.0.1;Port=3306;CharacterSet=utf8;PoolCount=5;DriverID=MySQL',
        ora_temp: 'Database=127.0.0.1:1521:kcaom1;User_Name=;Password=;CharacterSet=UTF8;PoolCount=5;DriverID=Ora',
        mssql_temp: 'Database=;User_Name=;Password=;Server=127.0.0.1;PoolCount=5;DriverID=MSSQL',
        pgsql_temp: 'User_Name=postgres;Password=;Database=;Server=127.0.0.1;Port=5432;CharacterSet=UTF8;PoolCount=5;DriverID=PostgreSQL'
      },
      // 表格渲染的数据
      paramTableInfo: {
        data: [],
        header: [
          {
            width: 150,
            prop: 'key',
            label: 'Key'
          },
          {
            prop: 'value',
            label: 'Value',
            showTooltip: 'noShow',
            render: (h, { row }) => {
              if (row.key === 'Password' || row.key === '密码') {
                return h(
                  'el-input',
                  {
                    on: {
                      input: (event) => {
                        row.value = event
                        this.inputPassWord = event
                      }
                    },
                    attrs: { type: 'password', value: row.value }
                  }
                )
              } else if (row.key === 'PoolCount') {
                return h(
                  'el-input',
                  {
                    on: {
                      input: (event) => {
                        row.value = event
                        this.inputNumber = event
                      }
                    },
                    attrs: { type: 'number', value: row.value }
                  }
                )
              } else {
                return h(
                  'el-input',
                  {
                    on: {
                      input: (event) => {
                        row.value = event
                        this.inputText = event
                      }
                    },
                    attrs: { type: 'text', value: row.value }
                  }
                )
              }
            }
          }

        ]
      },
      //   测试按钮点击需要用户等待的时间
      wait: 0,
      buileDatabaseParams: {
        visible: false
      }

    }
  },
  mounted() {
    this.rows = []
    this.initWindow()
  },
  destroyed() {
    this.$clearInterval()
  },
  methods: {
    //   建库模板
    onLibraryModuleClick() {
      this.buileDatabaseParams.visible = true
      this.buileDatabaseParams.title = '信息'
      this.buileDatabaseParams.driverID = this.formData.driverID
      this.buileDatabaseParams.confirm = () => {
        this.buileDatabaseParams.visible = false
      }
      //   this.buileDatabaseParams.visible = true
    },
    //    测试
    onTestClick() {
      if (this.wait === 0) {
        var vPar = new this.ParamArr()
        vPar.setBool('IsDetailed', this.params.g_data.name === '主库')
        if (vPar.getBool('IsDetailed')) {
          vPar.setStr('Detailed', this.getRowKeyValue('副库'))
          if (this.formData.driverID === 'PostgreSQL') {
            vPar.setStr('Detailed', 'copydb')
          }
          vPar.setStr('DetailedPass', this.getRowKeyValue('密码'))
        }
        vPar.setStr('Conn', this.getTableDataStr())
        dBConnectionTest(vPar).then((vPar) => {
          this.$message({
            message: '连接成功',
            type: 'success'
          })
        }).catch((a) => {
        })
        this.wait = 3
      } else {
        this.$message({
          message: '点击测试请求时间间隔3秒',
          type: 'warning'
        })
        var _this = this
        this.$setTimeout(function() { _this.wait = 0 }, 3000)
      }
    },
    // 获取处理后的数据
    getTableDataStr() {
      var arr = []
      for (let i = 0; i < this.paramTableInfo.data.length; i++) {
        if (this.paramTableInfo.data[i].key !== '副库' && this.paramTableInfo.data[i].key !== '密码') {
          arr.push(Global.strFormat('{0}={1}', this.paramTableInfo.data[i].key, this.paramTableInfo.data[i].value))
        }
      }
      arr.push('DriverID=' + this.formData.driverID)
      arr.push('')
      return arr.join('\r\n')
    },
    // 获取指定行数据
    getRowKeyValue(str) {
      const row = this.paramTableInfo.data.filter((item) => { return item.key === str })[0]
      const inputValue = row ? row.value : ''
      return inputValue
    },
    changeSelect(data) {
      if (data === 'Ora') {
        this.insertRows(this.tempDate.ora_temp)
      } else if (data === 'MSSQL') {
        this.insertRows(this.tempDate.mssql_temp)
      } else if (data === 'MySQL') {
        this.insertRows(this.tempDate.mysql_temp)
      } else if (data === 'PostgreSQL') {
        this.insertRows(this.tempDate.pgsql_temp)
      }
    },
    initWindow() {
      this.insertRows(this.params.g_data.paramName || this.tempDate.ora_temp)
      if (this.formData.driverID === 'Ora') {
        this.insertRows(this.tempDate.ora_temp)
      } else if (this.formData.driverID === 'MSSQL') {
        this.insertRows(this.tempDate.mssql_temp)
      } else if (this.formData.driverID === 'MySQL') {
        this.insertRows(this.tempDate.mysql_temp)
      } else if (this.formData.driverID === 'PostgreSQL') {
        this.insertRows(this.tempDate.pgsql_temp)
      }
    },
    insertRows(temp) {
      const vPar = new this.ParamArr()
      let type = 'Ora'
      let def = ''
      const paramName_driverID = this.params.g_data.paramName.substring(this.params.g_data.paramName.lastIndexOf('=') + 1).trim()
      const driverID = this.params.g_data.paramName.slice(this.params.g_data.paramName.lastIndexOf('=') + 1).trim() || 'Ora'
      if (driverID === paramName_driverID) {
        def = this.params.g_data.paramName.split('\r\n')
        if (def !== '') {
          def.pop()
          type = def[def.length - 1].split('=')[1]
          def.pop()
          temp = def.join(';')
        }
      } else {
        type = temp.substring(temp.lastIndexOf('=') + 1)
        temp = temp.substring(0, temp.lastIndexOf(';')) // 将driverID截取掉
      }

      temp = temp.split(';')
      this.rows = []
      for (var i = 0; i < temp.length; i++) {
        var t = temp[i].split('=')
        this.rows.push({ id: Global.getGuid(), key: t[0], value: t[1] })
      }
      if (this.params.g_data.name === '主库') {
        if (type === 'Ora') {
          this.rows.push({ id: Global.getGuid(), key: '副库', value: vPar.getStr('Detailed') })
          this.rows.push({ id: Global.getGuid(), key: '密码', value: vPar.getStr('DetailedPass') })
        } else if (type !== 'PostgreSQL') {
          this.rows.push({ id: Global.getGuid(), key: '副库', value: vPar.getStr('Detailed') })
        }
      }
      this.paramTableInfo.data = this.rows
    },
    confirm() {
      this.params.confirm(this.getTableDataStr())
    }
  }
}
</script>
<style lang='scss' scoped>
.btn-left{
    float: left;
}
</style>
